<script src="../../../api/system/role.js"></script>
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="考试名称" prop="examName">
        <el-input
          v-model="queryParams.examName"
          placeholder="请输入考试名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="所在班级">
        <el-select v-model="queryParams.classNumber" filterable clearable placeholder="请选择所在班级" @change="handleQuery">
          <el-option
            v-for="item in claassList"
            :key="item.id"
            :label="item.className"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <template v-if="userType !== '4'">
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:mark:add']"
          >新增</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"/>
      </el-row>
    </template>

    <el-table v-loading="loading" :data="markList" @selection-change="handleSelectionChange">
      <template v-if="userType !== '4'">
        <el-table-column type="selection" width="60" align="center" />
      </template>
      <el-table-column label="考试名称" align="center" prop="examName" />
      <el-table-column label="班级名称" align="center" prop="className" />
      <el-table-column label="班级科目" align="center" prop="courseName" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="showUserMark(scope.row)"
            v-hasPermi="['system:mark:edit']"
          >查看成绩</el-button>
         <template v-if="userType !== '4'">
           <el-button
             size="mini"
             type="text"
             icon="el-icon-tickets"
             @click="enterGrades(scope.row)"
             v-hasPermi="['system:mark:edit']"
           >录入成绩</el-button>
           <el-button
             size="mini"
             type="text"
             icon="el-icon-edit"
             @click="handleUpdate(scope.row)"
             v-hasPermi="['system:mark:edit']"
           >修改</el-button>
           <el-button
             size="mini"
             type="text"
             icon="el-icon-delete"
             @click="handleDelete(scope.row)"
             v-hasPermi="['system:mark:remove']"
           >删除</el-button>
         </template>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改学生成绩对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="考试班级" prop="classNumber">
          <el-select v-model="form.classNumber" filterable placeholder="请选择考试班级" :disabled="title === '修改考试信息'">
            <el-option
              v-for="item in claassList"
              :key="item.id"
              :label="item.className"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="考试名称" prop="examName">
          <el-input v-model="form.examName" placeholder="请输入考试名称" />
        </el-form-item>
        <el-form-item label="科目类别" prop="courseId">
          <el-radio-group v-model="form.courseId" :disabled="title === '修改考试信息'">
            <el-radio v-for="item in subjectList" :label="item.id" :key="item.id">
              {{ item.courseName }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--   编辑或查看学生成绩 -->
    <el-drawer
      :title="drawerTitle"
      :visible.sync="drawer"
      direction="rtl"
      :before-close="handleClose"
    >
      <el-table v-loading="loadingScore" :data="scoreList">
        <el-table-column label="学生" align="center" prop="nickName" />
        <el-table-column v-if="isLook"  label="成绩（分）" align="center" prop="courseMark"  >
          <template slot-scope="{ row, index }">
            <el-input v-model="row.courseMark"   :disabled="isLook" maxlength="3"></el-input>
          </template>
        </el-table-column>
        <template v-else>
          <el-table-column label="成绩（分）" align="center" prop="courseMark">
            <template slot-scope="{ row, index }">
              <el-input v-model="row.courseMark"  placeholder="请输入成绩" :disabled="isLook" maxlength="3"></el-input>
            </template>
          </el-table-column>
        </template>
      </el-table>
      <template v-if="!isLook && scoreList.length">
        <div style="display: flex; justify-content: flex-end; margin-top: 20px; width: 100%;">
          <el-button style="width: 150px;" @click="cancelEnter">取消</el-button>
          <el-button style="width: 150px;" type="primary" @click="submitStudentForm">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script>
import { listMark, getMark, delMark, addMark, updateMark,addStudentMark,listStudentMark,editStudentMark } from "@/api/system/mark";
import {getStudentByClass, listClaass} from "@/api/system/claass";
import {listType} from "@/api/system/courseType";
export default {
  name: "Mark",
  data() {
    return {
      isLook: false,
      scoreInfo: {},
      scoreList: [],
      loadingScore: false,
      drawer: false,
      score: [],
      userType: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 学生成绩表格数据
      markList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        courseName: null,
        userId: null,
        courseMark: null,
        classNumber: null,
        examName: null, // 考试名称
        examId:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      claassList: [],
      subjectList: [],
      drawerTitle: ''
    };
  },
  created() {
    this.getList();
    this.userType = localStorage.getItem('userType')
  },
  methods: {
    /** 查询学生成绩列表 */
    getList() {
      this.loading = true;
      listClaass({
        pageNum: 1,
        pageSize: 100,
      }).then(response => {
        this.claassList = response.rows;
      });
      listType({
          pageNum: 1,
          pageSize: 100,
      }).then(res => {
          this.subjectList = res.rows.filter(item => item.courseName.length < 4)
      })
      listMark(this.queryParams).then(response => {
        this.markList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        courseId: [],
        classNumber: null,
        examName:null  // 考试名称
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加考试";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      console.log("---->",row)
      const id = row.id
      getMark(id).then(response => {
        this.form = response.data;
        console.log("返回数据：",this.form)
        this.open = true;
        this.title = "修改考试信息";
      });
    },

    /** 根据用户id和考试id和班级 条件查看学生成绩 按钮操作 */
    showUserMark(row) {
      this.isLook = true
      this.drawerTitle = `查看学生成绩 （当前科目：${row.courseName}）`
      this.drawer = true
      this.scoreInfo = row
      this.loadingScore = true
      listStudentMark({
        ...this.queryParams,
        classNumber: row.classNumber,
        examId: row.examId,
        pageSize: 100
      }).then(res => {
        this.loadingScore = false
        this.scoreList = res.rows.map(item => {
          item.mark = ''
          return item
        })
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        console.log("===>",this.form)
        if (valid) {
          if (this.form.id != null) {
            updateMark(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addMark(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 提交按钮 */
    submitStudentForm() {
      console.log("--->",this.scoreList)
      console.log('this.scoreInfo', this.scoreInfo)
      const studentMark = this.scoreList.map(item =>{
        return {
          id: item.id,
          examId:this.scoreInfo.examId,
          examName:this.scoreInfo.examName,
          classNumber:this.scoreInfo.classNumber,
          courseId:this.scoreInfo.courseId,
          userId:item.userId,
          courseMark:item.courseMark
        }
      })
      editStudentMark(studentMark).then(() => {
            this.$modal.msgSuccess("保存成功");
            this.open = false;
            this.drawer = false
            this.getList();
          });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.examId
      this.$modal.confirm('是否确认删除考试名称为【' + row.examName + '】的考试？').then(function() {
        return delMark(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/mark/export', {
        ...this.queryParams
      }, `mark_${new Date().getTime()}.xlsx`)
    },
    /** 录入成绩 */
    enterGrades(row) {
      this.isLook = false
      this.drawer = true
      this.scoreInfo = row
      this.drawerTitle = `录入学生成绩 （当前科目：${row.courseName}）`
      this.loadingScore = true
      listStudentMark({
        ...this.queryParams,
        classNumber: row.classNumber,
        examId: row.examId,
        pageSize: 100
      }).then(res => {
        this.loadingScore = false
        this.scoreList = res.rows
      });
      // listStudentMark(row.examId).then(res => {
      //   this.loadingScore = false
      //   console.log("返回数据",res)
      //   this.scoreList = res.rows
      //   console.log("->>>",this.scoreList)
      // })
      // getStudentByClass(row.classNumber).then(res => {
      //   this.loadingScore = false
      //   this.scoreList = res.rows
      //   console.log("->>>",this.scoreList)
      // })
    },
    handleClose() {
      this.scoreInfo = {}
      this.drawer = false
      this.score = []
    },
    sure() {
      console.log(this.scoreList)
    },
    cancelEnter() {
      this.handleClose()
    }
  }
};
</script>

<style>
.el-radio-group {
  margin-top: 10px;
}

.el-radio {
  margin-bottom: 20px;
}

.el-drawer__header > :first-child {
  font-size: 16px;
}
</style>
